//
//  RHLoginViewController.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/5.
//

#import "RHLoginViewController.h"
#import "RHRegistViewController.h"
#import "NSAttributedString+YYText.h"
#import "RHForgotViewController.h"
#import "RHTabBarController.h"
#import "YYLabel.h"
#import "RHUserModel.h"
#import "RHChioceRegionTypeVC.h"
#import "RHGolbalRegionModel.h"
#import "RHGolbalServerModel.h"
#import "NetworkConfig.h"
#import "LCMD5Tool.h"
#import "RHTools.h"
#import "KWTButton.h"
#import "EnvironmentManage.h"

@interface RHLoginViewController ()

@property (nonatomic ,strong) UIView *contentView;

@property (nonatomic ,strong) UIImageView *logoView;

@property (nonatomic ,strong) NSMutableArray *TFArr;

//国家代码列表选择
@property (nonatomic ,strong) NSArray *countryCodeArr;

@property (nonatomic ,strong) NSMutableDictionary *para;

@property (nonatomic, strong) UIView *roleView;

@property (nonatomic, assign) BOOL isDemoAccount;//演示账号

@property (nonatomic, assign) NSInteger tapCount;

@property (nonatomic, assign) QMUIButton *enironmentBtn;

@property (nonatomic, strong) UIView *btnContentVeiw;

@end

@implementation RHLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    double value = 5.2066;
//    NSString *str1 = [NSDecimalNumber decimalPlacesWithoutRoundDownWithDigit:2 value:value];
//    NSLog(@"---------->不四舍五入保留小数后:%@",str1);
//    
//    NSString *str2 = [NSDecimalNumber decimalPlacesWithRoundUpWithDigit:2 value:value];
//    NSLog(@"---------->四舍五入保留小数后:%@",str2);
    
    [self setupUI];
    
    [self setLoginInfo];

}
-(NSMutableDictionary *)para
{
    if(!_para){
        _para = [NSMutableDictionary dictionary];
    }
    return _para;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}
#pragma mark ------ 获取全球国家地区及编码

-(void)getCountryRegionCode
{
    //根据全球国家编码
    [QMUITips showLoadingInView:self.view];
    [RHGolbalRegionModel startWithBaseUrl:[EnvironmentManage sharedEnvirManage].getBaseAPIUrl APIKey:G_getCountries argument:@{} requestMethod:RequestMethodPOST requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.countryCodeArr = resultModel.data;
            [self showCountryList];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

-(void)setLoginInfo{
    if([UserDefaults objectForKey:kCountry]&&[UserDefaults objectForKey:kRegionCode]){
//        [(QMUITextField*)self.TFArr[0] setText:[RHTools getRegionNameWithCode:[UserDefaults objectForKey:kRegionCode]]];//翻译
        [(QMUITextField*)self.TFArr[0] setText:[UserDefaults objectForKey:kCountry]];//不翻译
        
        [self.para setObject:[UserDefaults objectForKey:kRegionCode] forKey:@"regionCode"];
        [self.para setObject:[UserDefaults objectForKey:kCountry] forKey:@"country"];
    }
//    if([UserDefaults objectForKey:kEmail]){
//        [(QMUITextField*)self.TFArr[1] setText:[UserDefaults objectForKey:kEmail]];
//    }
    
    NSDictionary *dic = [RHTools getAccountInfo];
    if (dic[@"account"]) {
        [(QMUITextField*)self.TFArr[1] setText:dic[@"account"]];
    }
    if (dic[@"password"]) {
        [(QMUITextField*)self.TFArr[2] setText:dic[@"password"]];
    }
}

//注册成功后将信息回填登录页面
-(void)registerSuccess:(NSNotification*)no
{
    QMUITextField *countryTF = (QMUITextField*)self.TFArr[0];
//    countryTF.text = [RHTools getRegionNameWithCode:[no object][@"regionCode"]];//翻译
    countryTF.text = [no object][@"country"];//不翻译
    
    [self.para setObject:[no object][@"country"] forKey:@"country"];
    [self.para setObject:[no object][@"regionCode"] forKey:@"regionCode"];
    QMUITextField *emailTF = (QMUITextField*)self.TFArr[1];
    emailTF.text = [no object][@"email"];
}

- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registerSuccess:) name:@"UserRegisterSuccess" object:nil];
    
   
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:scrollView];
    scrollView.backgroundColor = [UIColor clearColor];
    if (@available(iOS 11.0, *)){
        scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    kWeakSelf;
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.view);
    }];
    scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = kCOLOR_HEX(@"F1FCF3");
    [scrollView addSubview:_contentView];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(scrollView);
        make.width.mas_equalTo(scrollView);
        make.height.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
    
    
    //logo 欢迎
    UIView *top_bgView = [[UIView alloc] init];
    [top_bgView setGradientBackgroundWithColors:@[kCOLOR_HEX(@"#6AD68A"),kCOLOR_HEX(@"#5FCCB4")] orientation:GradientOrientationLeftTopToRightBottom];
    [_contentView addSubview:top_bgView];
    [top_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_offset(0);
    }];
    
    
    UIImageView *logoImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_icon"]];
    [top_bgView addSubview:logoImg];
    [logoImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(0);
        make.size.equalTo(@(CGSizeMake(kScaleW(196), kScaleW(185))));
        make.top.mas_offset(kSafe_top);
        make.bottom.mas_offset(-50);
    }];
    
    //点击10下切换环境(非正式环境)
    if (Environment == 0) {
        UIView *tapView = kView;
//        tapView.backgroundColor = [UIColor grayColor];
        tapView.userInteractionEnabled = YES;
        [top_bgView addSubview:tapView];
        [tapView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.equalTo(@(CGSizeMake(80, kSafe_top+30)));
            make.top.right.mas_offset(0);
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
        [tapView addGestureRecognizer:tap];
    }
    
    
    QMUILabel *welcomeLab = [[QMUILabel alloc]init];
    welcomeLab.text = @"欢迎来到 Smart Energy".rh_localized;
    welcomeLab.numberOfLines = 0;
    welcomeLab.font = [UIFont boldSystemFontOfSize:24];
    welcomeLab.textColor = kCOLOR_HEX(@"#ffffff");
    welcomeLab.qmui_lineHeight = 45;
    [top_bgView addSubview:welcomeLab];
    [welcomeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(logoImg).offset(0);
        make.left.mas_offset(20);
       
    }];
    
    
    
    UIView *bg_view = [[UIView alloc] init];
    [bg_view setBackgroundColor:UIColor.clearColor];
    bg_view.layer.cornerRadius = 15;
    bg_view.layer.masksToBounds = YES;
    bg_view.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bg_view.clipsToBounds = YES;
    [_contentView addSubview:bg_view];
    [bg_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(top_bgView.mas_bottom).offset(-75);
       
    }];
    
    UIView *gradientView = kView;
    [gradientView setGradientBackgroundWithColors:@[kCOLOR_HEX_A(@"#FFFFFF",0.5),kCOLOR_HEX_A(@"#FFFFFF",0.8),kCOLOR_HEX_A(@"#FFFFFF",1),kCOLOR_HEX_A(@"#FFFFFF",1)] orientation:GradientOrientationTopToBottom locations:@[@(0),@(0.1),@(0.22),@(1)]];
    [bg_view addSubview:gradientView];
    [gradientView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
    }];
    
    //模糊蒙版本
    UIVisualEffectView *effctVeiw = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect qmui_effectWithBlurRadius:2]];
    [bg_view addSubview:effctVeiw];
    [effctVeiw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    QMUIButton *forgetBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [forgetBtn setTitle:@"忘记密码?".rh_localized forState:UIControlStateNormal];
    [forgetBtn setTitleColor:kCOLOR_HEX_A(@"#3DBB91", 1) forState:UIControlStateNormal];
    [forgetBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [forgetBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [bg_view addSubview:forgetBtn];
    
    [forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.bottom.mas_offset(-5);
        make.size.mas_equalTo(CGSizeMake(150, 30));
    }];
    
#pragma mark ----- 忘记密码
    [[forgetBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            RHForgotViewController *vc = [[RHForgotViewController alloc] init];
            vc.para = weakSelf.para;
            [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    self.TFArr = [NSMutableArray array];

    NSArray *titles = @[@"国家/地区".rh_localized,@"邮箱/账号名".rh_localized,@"请输入密码".rh_localized];
    NSArray *placeholders = @[@"请选择国家/地区".rh_localized,@"请输入邮箱或账号名称".rh_localized,@"请输入密码".rh_localized];
    NSMutableArray *array = [NSMutableArray array];
    [placeholders enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *view = [[UIView alloc] init];
        [view setBackgroundColor:UIColor.clearColor];
        [bg_view addSubview:view];
        [array addObject:view];
        
        
        QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#474B53") textAligment:NSTextAlignmentLeft];
        titleLab.text = titles[idx];
        [view addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10);
            make.left.mas_offset(5);
            make.right.mas_offset(0);
        }];
        
        UIView *textField_bg = [[UIView alloc] init];
        textField_bg.backgroundColor = UIColor.clearColor;
        
        
        [view addSubview:textField_bg];
        
        
        [textField_bg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(5);
            make.right.mas_offset(-5);
            make.top.equalTo(titleLab.mas_bottom).offset(5);
            make.bottom.mas_offset(-5);
        }];
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        textField.font = kSYSTEMFONT(14);
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [textField setPlaceholder:placeholders[idx]];
        textField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        textField.backgroundColor = UIColor.clearColor;
        textField.qmui_borderColor = kCOLOR_HEX(@"#CDD0D6");
        textField.qmui_borderWidth = 1;
        textField.qmui_borderPosition = QMUIViewBorderPositionTop|QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom;
        textField.layer.cornerRadius = 8;
        [textField_bg addSubview:textField];
        [self.TFArr addObject:textField];
        
        if(idx == 1){//邮箱
            textField.keyboardType = UIKeyboardTypeEmailAddress;
            textField.maximumTextLength = 64;
        }
        if(idx == 2){//密码
            textField.maximumTextLength = 16;
            textField.keyboardType = UIKeyboardTypeASCIICapable;
            textField.clearButtonMode = UITextFieldViewModeNever;
            QMUIButton *showPwdBtn = [[QMUIButton alloc]init];
            [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd"] forState:UIControlStateNormal];
            [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd_s"] forState:UIControlStateSelected];
            [textField_bg addSubview:showPwdBtn];
            [showPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(35);
                make.right.equalTo(textField).offset(-5);
                make.centerY.equalTo(textField);
            }];
            
            [[showPwdBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIButton * _Nullable x) {
                x.selected = !x.selected;
                textField.secureTextEntry = !x.selected;
            }];
        }
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(2, 0, 2, 0));
            make.height.offset(44);
        }];
        
        if(idx == 0){
            textField.userInteractionEnabled = NO;
            UIImageView *arrowImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nav_arrow_down"]];
            arrowImg.contentMode = UIViewContentModeScaleAspectFit;
            [textField_bg addSubview:arrowImg];
            [arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(15);
                make.right.mas_offset(-15);
                make.centerY.mas_offset(0);
            }];
            
            QMUIButton *countryBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
            [textField_bg addSubview:countryBtn];
            [countryBtn addTarget:self action:@selector(getCountryRegionCode) forControlEvents:UIControlEventTouchUpInside];
            [countryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.insets(UIEdgeInsetsZero);
            }];
        }
        
        if(idx == placeholders.count-1){
            textField.secureTextEntry = YES;
        }
        
    }];
    
    [array mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.right.mas_offset(-10);
    }];
    
    [array mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:10 leadSpacing:10 tailSpacing:40];
    
    
    
    UIView *foot_view = [[UIView alloc] init];
    [foot_view setBackgroundColor:UIColor.whiteColor];
    [_contentView addSubview:foot_view];
    
    
    QMUIButton *loginBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"登录".rh_localized forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [loginBtn setBackgroundColor:CMainColorGreen];
    [loginBtn.layer setCornerRadius:5];
    [loginBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [foot_view addSubview:loginBtn];
    
    YYLabel *contentL = [[YYLabel alloc] init];
    NSString *str = [NSString stringWithFormat:@"%@%@",@"还没有账号?".rh_localized,@"立即注册".rh_localized];
    //设置多行
    contentL.numberOfLines = 0;
    //这个属性必须设置，多行才有效
    contentL.preferredMaxLayoutWidth = SCREEN_WIDTH-30;
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
    attri.yy_lineSpacing = 8;
    attri.yy_alignment = NSTextAlignmentCenter;
    attri.yy_font = [UIFont systemFontOfSize:15];
    //FontColor(@"#3ECE80")
    attri.yy_color = [UIColor colorWithHexString:@"#666666"];
    NSRange range1 = [str rangeOfString:@"立即注册".rh_localized];

    [attri yy_setTextHighlightRange:range1 color:CMainColorGreen backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        RHRegistViewController *vc = [[RHRegistViewController alloc] init];
        vc.registerPara = weakSelf.para;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
    
    //用label的attributedText属性来使用富文本
    contentL.attributedText = attri;
    CGSize maxSize = CGSizeMake(SCREEN_WIDTH-30, MAXFLOAT);
    //计算文本尺寸
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attri];
    contentL.textLayout = layout;
    CGFloat introHeight = layout.textBoundingSize.height;
    
    [foot_view addSubview:contentL];

    //演示版本
//    UIView *demoView = [self addDemoView];
//    [foot_view addSubview:demoView];
    
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.top.mas_offset(70);
    }];
    
    [contentL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(loginBtn);
        make.top.equalTo(loginBtn.mas_bottom).offset(5);
        make.right.equalTo(loginBtn);
        make.height.mas_equalTo(30);
        make.bottom.mas_offset(-15);
    }];
    
//    [demoView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.mas_offset(0);
//        make.top.equalTo(contentL.mas_bottom).offset(kUI_WINDOW_H>=812?80:60);
//    }];
    
    [foot_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.top.equalTo(bg_view.mas_bottom);
        make.bottom.mas_offset(0);
        
    }];
    
    
    
#pragma mark ---- 登录 -----
    [[loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        
        if([[(QMUITextField*)weakSelf.TFArr[0] text]length] == 0){
            [QMUITips showError:@"请选择一个国家/地区".rh_localized];
            return;
        }
        
        //去除复制粘贴过来的空字符
        QMUITextField *nameTextField = (QMUITextField*)weakSelf.TFArr[1];
        if([nameTextField.text containsString:@" "]){
            nameTextField.text = [nameTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        }
        if([nameTextField.text length] == 0){
            [QMUITips showInfo:@"请输入邮箱".rh_localized];
            return;
        }
        
        //密码校验
        NSString *password =  [(QMUITextField*)weakSelf.TFArr[2] text];
        if(![NSString validatePassword:password]){
            [QMUITips showError:@"密码长度为8 ~ 16，必须包含大写字母、小写字母和数字".rh_localized];
            return;
        }
        
        
        
        
        NSDictionary *login_para = @{@"username":[(QMUITextField*)weakSelf.TFArr[1] text],
                                     @"password":[LCMD5Tool md5HexDigest:[(QMUITextField*)weakSelf.TFArr[2] text]]
        };
      
        [weakSelf.para addEntriesFromDictionary:login_para];
        
        //根据国家编码获取区域服务器
        [weakSelf getServerInfoFromCountryCode];
        
        
    }];
    
    //品牌id(测试用)
//    QMUIButton *brandBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
//    [brandBtn setTitle:@"选择品牌ID".rh_localized forState:UIControlStateNormal];
//    [brandBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [brandBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
//    [brandBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
//    brandBtn.backgroundColor = CFMainColor;
//    [self.view addSubview:brandBtn];
//    brandBtn.hidden = YES;
//    
//    [brandBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_offset(15);
//        make.right.mas_offset(-15);
//        make.bottom.equalTo(loginBtn.mas_top).offset(-15);
//        make.size.mas_equalTo(CGSizeMake(150, 40));
//    }];
//    NSArray *brandidArr = @[@"100000100000",@"120000100073",@"120000100012",@"120000100071"];
//    [[brandBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
//        RHChioceRegionTypeVC *vc = [[RHChioceRegionTypeVC alloc] initWithData:brandidArr];
//        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
//        kWeakSelf;
//        vc.selectBlock = ^(NSInteger index) {
//            [brandBtn setTitle:brandidArr[index] forState:UIControlStateNormal];
//            [NetworkConfig sharedConfig].brandID = brandidArr[index];
//        };
//    }];
    
    // --------切换环境
   
    QMUIButton *enironmentBtn = [[QMUIButton alloc]init];
    NSString *curEnironment = [[EnvironmentManage sharedEnvirManage] getCurrentEnvironment];
    [enironmentBtn setTitle:curEnironment forState:UIControlStateNormal];
    enironmentBtn.titleLabel.font = kSYSTEMFONT(15);
    enironmentBtn.imagePosition = QMUIButtonImagePositionRight;
    [enironmentBtn setTitleColor:kCOLOR_HEX(@"000000") forState:UIControlStateNormal];
    [enironmentBtn setImage:[UIImage imageNamed:@"nav_arrow_down"] forState:UIControlStateNormal];
    [foot_view addSubview:enironmentBtn];
    [enironmentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.bottom.equalTo(loginBtn.mas_top).offset(-5);
        make.width.offset(200);
        make.height.offset (35);
    }];
    [[enironmentBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSArray *eniArr = @[@"开发环境",@"测试环境",@"验收环境",@"线上环境"];
        RHChioceRegionTypeVC *choiseVC = [[RHChioceRegionTypeVC alloc]initWithData:eniArr];
        choiseVC.curContent = [[EnvironmentManage sharedEnvirManage] getCurrentEnvironment];
        choiseVC.selectBlock = ^(NSInteger index) {
            [enironmentBtn setTitle:eniArr[index] forState:UIControlStateNormal];
            [[EnvironmentManage sharedEnvirManage]changeEnvironment:index];
        };
        [[RHWindowTipManage shareWindowTipManage] showWithController:choiseVC];
    }];
    enironmentBtn.hidden = YES;
    self.enironmentBtn = enironmentBtn;
    if((!Environment)&&[kUserDefaults boolForKey:@"showEnvironment"]){
        enironmentBtn.hidden = NO;
    }
    //--------------
    
}


#pragma mark ---- 根据国家编码获取区域服务器
-(void)getServerInfoFromCountryCode
{
    if(!self.para[@"regionCode"]){
        [QMUITips showError:@"请选择一个国家/地区".rh_localized];
        return;
    }
    
    [QMUITips showLoading:@"获取地区服务器...".rh_localized inView:self.view];
    NSDictionary *para = @{@"countryCode":self.para[@"regionCode"],
                           @"brandId":[NetworkConfig sharedConfig].brandID,
                           @"requestType":@(1)
                          };
    [RHGolbalServerModel startWithBaseUrl:[EnvironmentManage sharedEnvirManage].getBaseAPIUrl APIKey:G_getServerInfo argument:para requestMethod:RequestMethodPOST requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if(resultModel.code == 200){
            [QMUITips showLoading:@"登录...".rh_localized inView:self.view];
            NSLog(@"----> login request agrument:%@",self.para);
            RHGolbalServerModel *serverModel = [resultModel.data yy_modelCopy];
            
            [NetworkConfig sharedConfig].baseUrl = serverModel.apiAddress;
            [NetworkConfig sharedConfig].areaCode = serverModel.areaCode;
            NSLog(@"---->登录的服务器地址:%@",serverModel.apiAddress);
            NSLog(@"---->登录的地区:%@",serverModel.areaCode);
            
            [BaseModel startWithCompletionAPIKey:H_login argument:self.para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                if(resultModel.code == 200){
                    //演示账号不保存登录信息
                    [UserDefaults setObject:resultModel.token forKey:kToken];
                    if(!self.isDemoAccount){
                        [UserDefaults setBool:YES forKey:kIsLogined];
                        [UserDefaults setObject:self.para[@"username"] forKey:kEmail];
                        
                       
                        if(self.para[@"country"]){
                            [UserDefaults setObject:self.para[@"country"] forKey:kCountry];
                        }
                        if(self.para[@"regionCode"]){
                            [UserDefaults setObject:self.para[@"regionCode"] forKey:kRegionCode];
                        }
                        [UserDefaults setObject:[(QMUITextField*)self.TFArr[2] text] forKey:kPassword];
                        //保存到钥匙串
                        [RHTools setAccount:[(QMUITextField*)self.TFArr[1] text] password:[(QMUITextField*)self.TFArr[2] text]];
                        [UserDefaults setObject:serverModel.apiAddress forKey:kServerApi];
                        [UserDefaults setObject:serverModel.areaCode forKey:kAreacode];
                        
                        [UserDefaults synchronize];
                    }
                    
                    
                    [QMUITips showLoadingInView:self.view];
                    //登录之后获取一下个人信息,更新品牌
                    [[PrivateMange share] getUserInfoSuccess:^(RHUserModel *userModel){
                        
                        RHTabBarController *tabController = [[RHTabBarController alloc] init];
                        tabController.hidesBottomBarWhenPushed = NO;
                        [[UIApplication sharedApplication].keyWindow setRootViewController:tabController];
                    }];
                    
                }
            } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
            }];
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}



#pragma mark ------- 登录

-(void)showCountryList
{
    [self.view endEditing:YES];
    NSMutableArray *countryArr = [NSMutableArray array];
    for (int i = 0; i<self.countryCodeArr.count; i++) {
        RHGolbalRegionModel *model = self.countryCodeArr[i];
//        [countryArr addObject:[RHTools getRegionNameWithCode:model.countryCode]];//翻译
        [countryArr addObject:model.countryName];
    }
    RHChioceRegionTypeVC *vc = [[RHChioceRegionTypeVC alloc] initWithData:countryArr];
    QMUITextField *countryTF = (QMUITextField*)self.TFArr[0];
    vc.curContent = countryTF.text;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    kWeakSelf;
    vc.selectBlock = ^(NSInteger index) {
        QMUITextField *tf = (QMUITextField*)weakSelf.TFArr[0];
        RHGolbalRegionModel *model = weakSelf.countryCodeArr[index];
//        tf.text = [RHTools getRegionNameWithCode:model.countryCode];//翻译
        tf.text = model.countryName;
        //国家区域编码
        [weakSelf.para setObject:model.countryName forKey:@"country"];
        [weakSelf.para setObject:model.countryCode forKey:@"regionCode"];
    };
}

-(void)tapAction
{
    NSLog(@"------>点击了");
    if(self.tapCount>10)return;
    self.tapCount ++;
    if (self.tapCount == 10) {
        [kUserDefaults setBool:YES forKey:@"showEnvironment"];
        self.enironmentBtn.hidden = NO;
    }
    
}


#pragma mark ------- 演示版本 -------------

-(UIView*)addDemoView
{
    
    kWeakSelf;
    UIView *bgView = kView;
    [self.view addSubview:bgView];
    bgView.backgroundColor = UIColor.clearColor;
    
    
    QMUILabel *demoLab = [[QMUILabel alloc]init];
    demoLab.text = @"演示版本".rh_localized;
    demoLab.textColor = [UIColor colorWithWhite:0 alpha:0.4];
    demoLab.font = kSYSTEMFONT(12);
    [bgView addSubview:demoLab];
    [demoLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.centerX.mas_offset(0);
    }];
    
    UIView *leftLine = kView;
    leftLine.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:leftLine];
    
    UIView *rightLine = kView;
    rightLine.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:rightLine];
    
    [leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(demoLab.mas_left).offset(-10);
        make.left.mas_offset(kScaleW(30));
        make.height.offset(1);
        make.centerY.equalTo(demoLab);
    }];
    
    [rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(demoLab.mas_right).offset(10);
        make.right.mas_offset(kScaleW(-30));
        make.height.offset(1);
        make.centerY.equalTo(demoLab);
    }];
    
    KWTButton *btn1 = [[KWTButton alloc]initWithImage:@"kwt_demo_install" title:@"安装商/服务".rh_localized];
    btn1.btnTitleLab.font = kSYSTEMFONT(14);
    btn1.btnTitleLab.textColor = kCOLOR_HEX(@"3F4443");
    btn1.backgroundColor = [UIColor colorWithHexString:@"DBECFF" alpha:0.25];
    btn1.layer.borderWidth = 1;
    btn1.layer.borderColor = kCOLOR_HEX_A(@"#7E868E", 0.16).CGColor;
    btn1.layer.cornerRadius = 8;
    btn1.layer.masksToBounds = YES;
    [bgView addSubview:btn1];
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.width.offset((kUI_WINDOW_W - 60)/2);
        make.top.equalTo(demoLab.mas_bottom).offset(10);
        make.height.offset(60);
        make.bottom.mas_offset(-30);
    }];
    
    KWTButton *btn2 = [[KWTButton alloc]initWithImage:@"kwt_demo_terminal" title:@"终端".rh_localized];
    btn2.btnTitleLab.font = kSYSTEMFONT(14);
    btn2.btnTitleLab.textColor = kCOLOR_HEX(@"3F4443");
    btn2.backgroundColor =  [UIColor colorWithHexString:@"DBECFF" alpha:0.25];
    btn2.layer.cornerRadius = 8;
    btn2.layer.borderWidth = 1;
    btn2.layer.borderColor = kCOLOR_HEX_A(@"#7E868E", 0.16).CGColor;
    btn2.layer.masksToBounds = YES;
    [bgView addSubview:btn2];
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(btn1.mas_right).offset(20);
        make.right.mas_offset(-20);
        make.top.equalTo(btn1);
        make.height.width.equalTo(btn1);
      
    }];
    
    [[btn1 rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf demo_loginWithEmail:@"InstallerDemo@163.com" password:@"Admin123"];
    }];
    
    [[btn2 rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf demo_loginWithEmail:@"EndExampl@163.com" password:@"Admin123"];
    }];
    
    return bgView;
}

-(void)demo_loginWithEmail:(NSString*)email password:(NSString *)password
{
    if(!self.para[@"regionCode"]){
        [QMUITips showError:@"请选择一个国家/地区".rh_localized];
        return;
    }
    self.isDemoAccount = YES;
    [self.para setObject:email forKey:@"username"];
    [self.para setObject:[LCMD5Tool md5HexDigest:password] forKey:@"password"];
    [self getServerInfoFromCountryCode];

}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
